package cn.felord.sse.api;

import cn.felord.sse.entity.MessageBody;
import cn.felord.sse.event.NewOrderNotifyEvent;
import cn.felord.sse.event.NewOrderNotifyEventPublisherAware;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author Dax
 * @since 09:43  2019/8/22
 */
@Controller
public class SseApi {
    private Map<String, SseEmitter> sseEmitters = new HashMap<>();
    @Resource
    private NewOrderNotifyEventPublisherAware newOrderNotifyEventPublisherAware;

    @GetMapping(path = "/events/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @CrossOrigin
    public SseEmitter handle(@PathVariable String id) {
        SseEmitter sseEmitter = new SseEmitter();
        this.sseEmitters.put(id, sseEmitter);
        return sseEmitter;
    }


    @GetMapping("/send/{id}")

    public void send(@PathVariable String id){



        Map<String, String> map = new HashMap<>(1);

        map.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        MessageBody<Map<String, String>> body = new MessageBody<>();

        body.setFrom("SERVER");
        body.setTo(id);
        body.setPayload(map);

        Optional.of(sseEmitters.get(id)).ifPresent(sseEmitter -> {
            NewOrderNotifyEvent newOrderNotifyEvent = new NewOrderNotifyEvent(false, body, sseEmitter);
            newOrderNotifyEventPublisherAware.publish(newOrderNotifyEvent);
        });

    }


    @GetMapping("/index")
    public String index() {
        return "index";
    }
}
